package com.loan.system.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.loan.common.core.domain.PageQuery;
import com.loan.common.core.domain.entity.SysUser;
import com.loan.common.core.domain.model.LoginUser;
import com.loan.common.core.page.TableDataInfo;
import com.loan.common.helper.LoginHelper;
import com.loan.common.utils.DateUtils;
import com.loan.common.utils.StringUtils;
import com.loan.system.domain.*;
import com.loan.system.mapper.ApplyMapper;
import com.loan.system.mapper.OverConfigMapper;
import com.loan.system.mapper.OverOneDataMapper;
import com.loan.system.mapper.UserOverMapper;
import com.loan.system.service.CompanyService;
import com.loan.system.service.ISysUserService;
import com.loan.system.service.OverOneDataService;
import com.loan.system.service.UserOverService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author shiguang on 2022/10/9 17:00
 */
@Service
@RequiredArgsConstructor
public class OverOneDataServiceImpl implements OverOneDataService {

    private final ApplyMapper applyMapper;

    private final OverOneDataMapper overOneDataMapper;

    private final ISysUserService userService;

    private final CompanyService companyService;

    private final OverConfigMapper overConfigMapper;

    private final UserOverMapper userOverMapper;

    @Override
    public void addOneOverData() {

        String buildDate = DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD);
        //获取所有公司
        List<CompanyEntity> companyEntityList = companyService.selectList();
        for (CompanyEntity companyEntity : companyEntityList) {
            //获取该公司下最小的催收配置
            OverConfigEntity overConfigEntity = overConfigMapper.selectOne(new QueryWrapper<OverConfigEntity>()
                    .eq("company_id", companyEntity.getId())
                    .eq("del_flag", 0)
                    .orderByAsc("min_day")
                    .last("limit 1"));
            if (ObjectUtil.isNotNull(overConfigEntity)) {
                //获取最小天数和最大天数
                Integer minDay = overConfigEntity.getMinDay();
                Integer maxDay = overConfigEntity.getMaxDay();
                //获取该配置绑定的催收用户
                List<UserOverEntity> userOverEntityList = userOverMapper.selectList(new QueryWrapper<UserOverEntity>().eq("over_config_id", overConfigEntity.getId()));
                for (UserOverEntity userOverEntity : userOverEntityList) {
                    //获取该催收用户当前的总订单数(不包括当天分配的订单)
                    long num = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                            .eq("collection_by", userOverEntity.getUserId())
                            .in("status", "6", "8")
                            .lt("over_examine_time", DateUtils.toBeginDateByDay(buildDate))
                    );
                    //当天到期单数
                    long numDay = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                            .eq("collection_by", userOverEntity.getUserId())
                            .eq("repayment_time", DateUtils.getDate()));
                    //当天新增单数
                    long addNum = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                            .eq("collection_by", userOverEntity.getUserId())
                            .between("over_examine_time",  DateUtils.toBeginDateByDay(buildDate),DateUtils.toEndDateByDay(buildDate))
                    );
                    //当天到期还款单数
//                    long repaymentNumDay = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
//                            .eq("collection_by", userOverEntity.getUserId())
//                            .eq("status", "7")
//                            .between("already_repay_time", DateUtils.toBeginDateByDay(new Date()), DateUtils.toEndDateByDay(new Date())));
//                    //当天还款单数
                    long repaymentNum = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                            .eq("collection_by", userOverEntity.getUserId())
                            .between("already_repay_time", DateUtils.toBeginDateByDay(buildDate), DateUtils.toEndDateByDay(buildDate))
                            .eq("status", "7"));
                    //当天应还本金
                    long repaymentAmount = applyMapper.selectRepaymentByDate(userOverEntity.getUserId(), buildDate);
                    //当天还款金额
                    long alreadyRepayMoney = applyMapper.selectCallMoneyByDate(userOverEntity.getUserId(), buildDate);
                    //-1到期单数
                    long tomorrowNum = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                            .eq("collection_by", userOverEntity.getUserId())
                            .eq("repayment_time", DateUtils.dateTime(DateUtils.addDays(new Date(), 1))));
                    //-1到期本金
                    long tomorrowRepayment = applyMapper.selectRepaymentByDate(userOverEntity.getUserId(), DateUtils.dateTime(DateUtils.addDays(new Date(), 1)));
                    // -1本金催回
                    long tomorrowAlreadyRepayment = applyMapper.selectTomorrowAlreadyAmount(userOverEntity.getUserId(), DateUtils.dateTime(DateUtils.addDays(new Date(), 1)));
                    //当日触达订单数
                    long dayRemarkNum = applyMapper.selectDayRemark(userOverEntity.getUserId(), buildDate);

                    OverOneDataEntity entity = overOneDataMapper.selectOne(new QueryWrapper<OverOneDataEntity>().eq("build_date", buildDate).eq("user_id", userOverEntity.getUserId()));
                    if (ObjectUtil.isNull(entity)) {
                        entity = new OverOneDataEntity();
                        entity.setTotalNum(Math.toIntExact(num));
                    }
                    entity.setCompanyId(companyEntity.getId());
                    entity.setUserId(userOverEntity.getUserId());
                    entity.setExpireDay(Math.toIntExact(numDay));
                    entity.setExpirePayDay(Math.toIntExact(repaymentNum));
                    entity.setExpireMoneyDay(Math.toIntExact(alreadyRepayMoney));
                    entity.setDayMoney(Math.toIntExact(repaymentAmount));
                    entity.setBeforeDayMoney(Math.toIntExact(tomorrowAlreadyRepayment));
                    entity.setBeforeDayRepayMoney(Math.toIntExact(tomorrowRepayment));
                    entity.setBeforeDayNum(Math.toIntExact(tomorrowNum));
                    entity.setDayRemarkNum(Math.toIntExact(dayRemarkNum));
                    entity.setCreateTime(new Date());
                    entity.setBuildDate(buildDate);
                    entity.setAddNum(Math.toIntExact(addNum));

                    overOneDataMapper.insertOrUpdate(entity);
                }
            }
        }
//        List<Map<String, Object>> list = applyMapper.selectOneOverDataByData(buildDate, null);
//        for (Map<String, Object> map : list) {
//            OverOneDataEntity entity = new OverOneDataEntity();
//            entity.setCompanyId(Long.valueOf(map.get("companyId").toString()));
//            entity.setUserId(Long.valueOf(map.get("collectionBy").toString()));
//            entity.setTotalNum(Integer.valueOf(map.get("num1").toString()));
//            entity.setExpireDay(Integer.valueOf(map.get("num2").toString()));
//            entity.setExpirePayDay(Integer.valueOf(map.get("num4").toString()));
//            entity.setExpireMoneyDay(Integer.valueOf(map.get("repayMoney").toString()));
//            entity.setDayMoney(Integer.valueOf(map.get("repaymentMoney").toString()));
//            entity.setBeforeDayMoney(Integer.valueOf(map.get("beforeRepayMoney").toString()));
//            entity.setBeforeDayRepayMoney(Integer.valueOf(map.get("beforeMoney").toString()));
//            entity.setBeforeDayNum(Integer.valueOf(map.get("num3").toString()));
//            entity.setDayRemarkNum(Integer.valueOf(map.get("num5").toString()));
//            entity.setCreateTime(new Date());
//            entity.setBuildDate(buildDate);
//            overOneDataMapper.insert(entity);
//        }
    }

    @Override
    public TableDataInfo<OverOneDataEntity> selectPageOverOneDataList(String beginTime, String endTime, Long userId, PageQuery pageQuery) {
//        List<OverOneDataEntity> entityList = new ArrayList<>();
//        String buildDate = DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD);
//        List<Map<String, Object>> list = applyMapper.selectOneOverDataByData(buildDate, userId);
//        if (StringUtils.isBlank(beginTime) && StringUtils.isBlank(endTime)) {
//            for (Map<String, Object> map : list) {
//                OverOneDataEntity entity = new OverOneDataEntity();
//                entity.setCompanyId(Long.valueOf(map.get("companyId").toString()));
//                entity.setUserId(Long.valueOf(map.get("collectionBy").toString()));
//                entity.setTotalNum(Integer.valueOf(map.get("num1").toString()));
//                entity.setExpireDay(Integer.valueOf(map.get("num2").toString()));
//                entity.setExpirePayDay(Integer.valueOf(map.get("num4").toString()));
//                entity.setExpireMoneyDay(Integer.valueOf(map.get("repayMoney").toString()));
//                entity.setDayMoney(Integer.valueOf(map.get("repaymentMoney").toString()));
//                entity.setBeforeDayMoney(Integer.valueOf(map.get("beforeRepayMoney").toString()));
//                entity.setBeforeDayRepayMoney(Integer.valueOf(map.get("beforeMoney").toString()));
//                entity.setBeforeDayNum(Integer.valueOf(map.get("num3").toString()));
//                entity.setDayRemarkNum(Integer.valueOf(map.get("num5").toString()));
//                entity.setCreateTime(new Date());
//                entity.setBuildDate(buildDate);
//                entityList.add(entity);
//            }
//        } else {
//            entityList = overOneDataMapper.selectListByTime(beginTime, endTime, userId);
//        }
//        for (OverOneDataEntity entity : entityList) {
//            SysUser user = userService.selectUserById(entity.getUserId());
//            entity.setUserName(user.getUserName());
//            CompanyEntity companyEntity = companyService.selectCompanyById(entity.getCompanyId());
//            entity.setCompanyName(companyEntity.getName());
//        }
//        return entityList;
        Page<OverOneDataEntity> page = overOneDataMapper.selectPageList(pageQuery.build(), this.buildQueryWrapper(beginTime, endTime, userId));
        return TableDataInfo.build(page);
    }

    private Wrapper<OverOneDataEntity> buildQueryWrapper(String beginTime, String endTime, Long userId) {
        QueryWrapper<OverOneDataEntity> wrapper = Wrappers.query();
        Long companyId = LoginHelper.getCompanyId();
        wrapper.eq(ObjectUtil.isNotNull(userId), "vod.user_id", userId)
                .eq(ObjectUtil.isNotNull(companyId), "vod.company_id", companyId)
                .between(StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime), "vod.build_date", beginTime, endTime)
                .orderByDesc("vod.build_date")
                .orderByAsc("vod.company_id")
                .orderByAsc("vod.user_id")
        ;
        return wrapper;
    }

    @Override
    public List<SysUser> listOverUser() {
        List<SysUser> list = new ArrayList<>();
        Long userId = LoginHelper.getUserId();
        SysUser sysUser = userService.selectUserById(userId);
        if (sysUser.getIsManage().equals("0") && sysUser.getCollection().equals("1")) {
            list.add(sysUser);
            return list;
        }

        List<Long> ids = overOneDataMapper.selectOverUserList();
        for (Long id : ids) {
            SysUser user = userService.selectUserById(id);
            list.add(user);
        }
        return list;
    }

    @Override
    public List<OverOneDataEntity> selectList(String beginTime, String endTime, String userId) {
        Long companyId = LoginHelper.getCompanyId();
        List<OverOneDataEntity> list = overOneDataMapper.selectList(new QueryWrapper<OverOneDataEntity>()
                .eq(ObjectUtil.isNotNull(userId), "user_id", userId)
                .eq(ObjectUtil.isNotNull(companyId), "company_id", companyId)
                .between(StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime), "build_date", beginTime, endTime)
                .orderByDesc("build_date")
                .orderByAsc("company_id")
                .orderByAsc("user_id")
        );
        for (OverOneDataEntity entity : list) {
            SysUser user = userService.selectByUserId(entity.getUserId());
            entity.setUserName(user.getUserName());
            CompanyEntity companyEntity = companyService.selectCompanyById(entity.getCompanyId());
            entity.setCompanyName(companyEntity.getName());
        }
        return list;
    }
}
